#!/bin/bash

# Functions.
help () {
printf "Use the -d option to quickly read the database (e.g. ./script -d).\n"
exit 0
}

# Options.
case $1 in
    -d)
        sqlite3 \
            -header -column \
            ffstats.db \
            "select * from stats;"
        exit 0
        ;;
     ?)
        help
        ;;
    -?)
        help
        ;;
esac

# Initialize cookie for use.
curl -s \
    --insecure \
    --cookie-jar funfile \
    --output /dev/null \
        https://funfile.org/login.php

# Pass expected data to FunFile.org.
curl -s \
    --insecure --cookie funfile --cookie-jar funfile \
    --data 'username=' \
    --data 'password=' \
    --data 'login=Login' \
    --data 'returnto=/' \
    --location \
    --output index.php \
        https://funfile.org/takelogin.php

# Create SQLite database if needed.
if [ ! -w ffstats.db ] ; then
    sqlite3 ffstats.db "create table stats ( \
        id integer primary key, \
        date, \
        time, \
        rank, \
        invites, \
        credits, \
        up, \
        down, \
        ratio \
        );"
fi

# Really sloppy variables.
STATS_A=`grep mycredits.php index.php | sed -n '/^$/!{s/<[^>]*>//g;p;}'`
STATS_B=`grep up index.php |grep down |grep ratio | sed -n '/^$/!{s/<[^>]*>//g;p                          ;}' \
    |awk -F ',' '{ print $1 "," $2 }' |sed -e 's/Total://'`
STATS_C=`grep up index.php |grep down |grep ratio | sed -n '/^$/!{s/<[^>]*>//g;p                          ;}'`
DATE=`date +"%m/%d"`
TIME=`date +"%T"`
RANK=`echo $STATS_A |awk -F ',' '{print $1}'`
INV=`echo $STATS_A |awk -F ',' '{print $2}' |awk '{print $1}'`
CRED=`echo $STATS_A |awk '{print $(NF-1)}'`
UP=`echo $STATS_B |awk '{print $1 $2}'`
DOWN=`echo $STATS_B |awk '{print $4 $5}'`
RATIO=`echo $STATS_C |awk '{print $8 ":1" }' |sed 's/ //g'`

# Populate SQLite tables.
sqlite3 ffstats.db "insert into stats \
    ('date','time','rank','invites','credits','up','down','ratio') \
    values ('${DATE}','${TIME}','${RANK}','${INV}','${CRED}','${UP}','${DOWN}','${RATIO}') \
;"
# Clean up and exit.
sqlite3 ffstats.db "delete from stats where ratio = ':1';"
rm index.php funfile
exit 0
